const { Weather, Forecast } = require('../models');
const { Op } = require('sequelize');
const weatherApi = require('../utils/weatherApi');

// 城市搜索
exports.searchCity = async (req, res) => {
  try {
    const { location, adm, range, number } = req.query;
    
    if (!location) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供location参数'
      });
    }
    
    // 调用和风天气API搜索城市
    const cityData = await weatherApi.searchCity(location, {
      adm,
      range: range || 'cn',
      number: number ? parseInt(number) : 10
    });
    
    // 直接返回和风天气API的响应
    res.status(200).json(cityData);
  } catch (error) {
    console.error('城市搜索失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 获取城市天气数据
exports.getWeather = async (req, res) => {
  try {
    const { city, province } = req.params;
    
    if (!city || !province) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供城市和省份'
      });
    }
    
    // 先从数据库查询是否有该城市的天气数据
    const cachedWeather = await Weather.findOne({
      where: { city, province },
      include: [{
        model: Forecast,
        as: 'forecasts'
      }]
    });
    
    // 检查数据是否存在且更新时间是否在30分钟内
    const now = new Date();
    const thirtyMinutesAgo = new Date(now.getTime() - 30 * 60 * 1000);
    
    // 如果有缓存数据且更新时间在30分钟内，且预报数据存在，直接返回缓存数据
    if (cachedWeather && 
        new Date(cachedWeather.updateTime) > thirtyMinutesAgo && 
        cachedWeather.forecasts && 
        cachedWeather.forecasts.length > 0) {
      console.log(`使用缓存的天气数据，城市: ${city}, 更新时间: ${cachedWeather.updateTime}`);
      
      return res.status(200).json({
        status: 'success',
        data: {
          weather: cachedWeather,
          source: '数据库缓存'
        }
      });
    }
    
    // 没有缓存、缓存已过期或没有预报数据，需要请求新数据
    try {
      // 1. 搜索城市获取ID
      const cityData = await weatherApi.searchCity(city, { adm: province });
      if (!cityData.location || cityData.location.length === 0) {
        throw new Error('找不到该城市');
      }
      
      const locationId = cityData.location[0].id;
      console.log(`获取到城市 ${city} 的ID: ${locationId}`);
      
      // 2. 获取实时天气
      const realTimeData = await weatherApi.getRealTimeWeather(locationId);
      console.log(`成功获取实时天气数据`);
      
      // 3. 获取天气预报 (修改为7天)
      const forecastData = await weatherApi.getWeatherForecast(locationId, 7);
      console.log(`成功获取天气预报数据`);
      
      // 4. 获取空气质量
      let airQualityData = null;
      try {
        airQualityData = await weatherApi.getAirQuality(locationId);
        console.log(`成功获取空气质量数据`);
      } catch (error) {
        console.error('获取空气质量失败，将继续处理其他数据:', error.message);
      }
      
      // 5. 转换数据格式
      const weatherData = weatherApi.convertWeatherData(realTimeData, forecastData, airQualityData);
      
      // 6. 保存到数据库（设置北京时间格式）
      const beijingTime = getBeijingTime();
      const updateTime = new Date(beijingTime);
      
      // 如果已有记录则更新，否则创建新记录
      let weather;
      if (cachedWeather) {
        await cachedWeather.update({
          temperature: weatherData.temperature,
          temperatureFeelsLike: weatherData.temperatureFeelsLike,
          temperatureHigh: weatherData.temperatureHigh,
          temperatureLow: weatherData.temperatureLow,
          humidity: weatherData.humidity,
          windSpeed: weatherData.windSpeed,
          windDirection: weatherData.windDirection,
          weatherCondition: weatherData.weatherCondition,
          aqi: weatherData.aqi,
          airQualityLevel: weatherData.airQualityLevel,
          pm25: weatherData.pm25,
          pm10: weatherData.pm10,
          updateTime
        });
        weather = cachedWeather;
      } else {
        weather = await Weather.create({
          city,
          province,
          temperature: weatherData.temperature,
          temperatureFeelsLike: weatherData.temperatureFeelsLike,
          temperatureHigh: weatherData.temperatureHigh,
          temperatureLow: weatherData.temperatureLow,
          humidity: weatherData.humidity,
          windSpeed: weatherData.windSpeed,
          windDirection: weatherData.windDirection,
          weatherCondition: weatherData.weatherCondition,
          aqi: weatherData.aqi,
          airQualityLevel: weatherData.airQualityLevel,
          pm25: weatherData.pm25,
          pm10: weatherData.pm10,
          date: new Date(),
          updateTime
        });
      }
      
      // 7. 更新天气预报
      // 先删除旧的预报数据
      await Forecast.destroy({
        where: { weatherId: weather.id }
      });
      
      // 添加新的预报数据，确保保存所有必要的字段
      const forecastPromises = weatherData.forecast.map(forecast => {
        return Forecast.create({
          weatherId: weather.id,
          date: new Date(forecast.date),
          sunrise: forecast.sunrise,
          sunset: forecast.sunset,
          temperatureHigh: forecast.temperatureHigh,
          temperatureLow: forecast.temperatureLow,
          weatherCondition: forecast.weatherCondition,
          weatherConditionNight: forecast.weatherConditionNight,
          textDay: forecast.textDay,
          textNight: forecast.textNight,
          windSpeed: forecast.windSpeed,
          windDirection: forecast.windDirection,
          windScale: forecast.windScale,
          windSpeedNight: forecast.windSpeedNight,
          windDirectionNight: forecast.windDirectionNight,
          windScaleNight: forecast.windScaleNight,
          humidity: forecast.humidity,
          precipitation: forecast.precipitation,
          pressure: forecast.pressure,
          visibility: forecast.visibility,
          uvIndex: forecast.uvIndex,
          probability: forecast.probability
        });
      });
      
      await Promise.all(forecastPromises);
      
      // 8. 重新查询带有预报的完整天气数据
      const completeWeather = await Weather.findByPk(weather.id, {
        include: [{
          model: Forecast,
          as: 'forecasts'
        }]
      });
      
      return res.status(200).json({
        status: 'success',
        data: {
          weather: completeWeather,
          source: '和风天气API'
        }
      });
    } catch (error) {
      console.error('和风天气API调用失败:', error.message);
      
      // 如果API调用失败但有缓存数据，仍然返回缓存数据（即使过期）
      if (cachedWeather) {
        console.log(`API调用失败，使用过期的缓存数据`);
        return res.status(200).json({
          status: 'success',
          data: {
            weather: cachedWeather,
            source: '过期的数据库缓存'
          }
        });
      }
      
      return res.status(500).json({
        status: 'error',
        message: `获取天气数据失败: ${error.message}`
      });
    }
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 创建或更新天气数据
exports.updateWeather = async (req, res) => {
  try {
    const { city, province, forecast, ...weatherData } = req.body;
    
    if (!city || !province) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供城市和省份'
      });
    }
    
    // 使用upsert：如果找不到记录则创建新记录
    let weather = await Weather.findOne({
      where: { city, province }
    });
    
    if (weather) {
      // 更新现有天气记录
      await weather.update({
        ...weatherData,
        updateTime: new Date()
      });
    } else {
      // 创建新天气记录
      weather = await Weather.create({
        city,
        province,
        ...weatherData,
        updateTime: new Date()
      });
    }
    
    // 如果提供了预报数据，则创建或更新预报
    if (forecast && Array.isArray(forecast) && forecast.length > 0) {
      // 先删除该天气ID的所有预报
      await Forecast.destroy({
        where: {
          weatherId: weather.id
        }
      });
      
      // 创建新的预报
      const forecastPromises = forecast.map(item => {
        return Forecast.create({
          weatherId: weather.id,
          date: item.date,
          temperatureHigh: item.temperatureHigh,
          temperatureLow: item.temperatureLow,
          weatherCondition: item.weatherCondition,
          windSpeed: item.windSpeed,
          windDirection: item.windDirection,
          probability: item.probability
        });
      });
      
      await Promise.all(forecastPromises);
    }
    
    // 重新查询带有预报的完整天气数据
    const completeWeather = await Weather.findByPk(weather.id, {
      include: [{
        model: Forecast,
        as: 'forecasts'
      }]
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        weather: completeWeather
      }
    });
  } catch (error) {
    res.status(400).json({
      status: 'fail',
      message: error.message
    });
  }
};

// 获取多个城市天气数据
exports.getMultiCityWeather = async (req, res) => {
  try {
    const { cities } = req.body;
    
    if (!cities || !Array.isArray(cities) || cities.length === 0) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供城市列表'
      });
    }
    
    // 先从数据库中获取所有缓存的天气数据
    const now = new Date();
    const thirtyMinutesAgo = new Date(now.getTime() - 30 * 60 * 1000);
    
    // 创建一个OR条件查询
    const whereConditions = cities.map(({ city, province }) => ({
      [Op.and]: [{ city }, { province }]
    }));
    
    const cachedWeatherData = await Weather.findAll({
      where: {
        [Op.or]: whereConditions
      },
      order: [['updateTime', 'DESC']]
    });
    
    // 创建结果对象，保存所有城市的天气数据
    const results = [];
    const citiesToFetch = [];
    
    // 遍历请求的城市列表
    for (const cityInfo of cities) {
      const { city, province } = cityInfo;
      
      // 查找缓存数据
      const cachedCity = cachedWeatherData.find(w => 
        w.city === city && w.province === province && 
        new Date(w.updateTime) > thirtyMinutesAgo
      );
      
      if (cachedCity) {
        // 有缓存且未过期，直接使用缓存
        results.push({
          ...cachedCity.toJSON(),
          source: '数据库缓存'
        });
      } else {
        // 需要获取最新数据
        citiesToFetch.push(cityInfo);
      }
    }
    
    // 对需要获取最新数据的城市进行API调用
    if (citiesToFetch.length > 0) {
      const newDataPromises = citiesToFetch.map(async ({ city, province }) => {
        try {
          // 1. 搜索城市获取ID
          const cityData = await weatherApi.searchCity(city, { adm: province });
          if (!cityData.location || cityData.location.length === 0) {
            return {
              city,
              province,
              error: '找不到该城市'
            };
          }
          
          const locationId = cityData.location[0].id;
          
          // 2. 获取实时天气
          const realTimeData = await weatherApi.getRealTimeWeather(locationId);
          
          // 3. 获取基本数据
          const now = realTimeData.now;
          const weatherCondition = weatherApi.iconCodeToWeatherCondition(now.icon);
          
          // 4. 设置北京时间
          const beijingTime = getBeijingTime();
          const updateTime = new Date(beijingTime);
          
          // 5. 保存到数据库
          let weatherRecord = await Weather.findOne({
            where: { city, province }
          });
          
          const weatherData = {
            temperature: parseFloat(now.temp),
            temperatureFeelsLike: parseFloat(now.feelsLike),
            humidity: parseFloat(now.humidity),
            windSpeed: parseFloat(now.windSpeed),
            windDirection: now.windDir,
            windScale: now.windScale,
            weatherCondition: weatherCondition,
            icon: now.icon,
            text: now.text,
            updateTime
          };
          
          if (weatherRecord) {
            // 更新现有天气记录
            await weatherRecord.update(weatherData);
          } else {
            // 创建新天气记录
            weatherRecord = await Weather.create({
              city,
              province,
              date: new Date(),
              ...weatherData
            });
          }
          
          // 返回新获取的数据
          return {
            ...weatherRecord.toJSON(),
            source: '和风天气API'
          };
        } catch (error) {
          console.error(`获取城市 ${city} 天气失败:`, error.message);
          
          // 查找过期的缓存数据
          const expiredCache = cachedWeatherData.find(w => 
            w.city === city && w.province === province
          );
          
          if (expiredCache) {
            return {
              ...expiredCache.toJSON(),
              source: '过期的数据库缓存'
            };
          }
          
          return {
            city,
            province,
            error: error.message
          };
        }
      });
      
      const newWeatherData = await Promise.all(newDataPromises);
      results.push(...newWeatherData);
    }
    
    res.status(200).json({
      status: 'success',
      results: results.length,
      data: {
        weather: results
      }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

// 获取热门城市天气
exports.getPopularCityWeather = async (req, res) => {
  try {
    // 从请求中获取参数
    const { range, number, lang } = req.query;
    
    // 定义缓存时间
    const now = new Date();
    const thirtyMinutesAgo = new Date(now.getTime() - 30 * 60 * 1000);
    
    // 查询数据库中的热门城市数据
    // 这里简单处理，获取最近更新的城市作为热门城市
    const cachedPopularCities = await Weather.findAll({
      where: {
        updateTime: {
          [Op.gt]: thirtyMinutesAgo
        }
      },
      order: [['updateTime', 'DESC']],
      limit: number ? parseInt(number) : 10
    });
    
    // 如果缓存中有足够的热门城市数据，直接返回
    if (cachedPopularCities.length >= (number ? parseInt(number) : 10)) {
      // 转换为和风天气API的响应格式
      const formattedResponse = {
        code: "200",
        topCityList: cachedPopularCities.map(city => ({
          name: city.city,
          id: city.id.toString(),
          lat: "0", // 这里可以添加经纬度字段
          lon: "0",
          adm2: city.city,
          adm1: city.province,
          country: "中国",
          // 添加天气信息
          temperature: city.temperature,
          weatherCondition: city.weatherCondition,
          text: city.weatherCondition,
          icon: getIconCodeFromWeatherCondition(city.weatherCondition)
        })),
        refer: {
          sources: ["本地数据库"],
          license: ["内部使用"]
        }
      };
      
      console.log('使用数据库缓存的热门城市数据');
      return res.status(200).json(formattedResponse);
    }
    
    // 缓存不足或过期，使用和风天气API获取热门城市列表
    const topCitiesData = await weatherApi.getTopCities({
      range: range || 'cn',
      number: number ? parseInt(number) : 10,
      lang: lang || 'zh'
    });

    if (!topCitiesData || !topCitiesData.topCityList || topCitiesData.topCityList.length === 0) {
      return res.status(404).json({
        status: 'fail',
        message: '获取热门城市列表失败'
      });
    }

    // 获取每个城市的天气数据并添加到响应中
    const enrichedTopCities = await Promise.all(
      topCitiesData.topCityList.map(async (city) => {
        try {
          // 查询数据库是否有该城市的天气数据
          const cachedWeather = await Weather.findOne({
            where: { city: city.name, province: city.adm1 }
          });
          
          // 如果有缓存且更新时间在30分钟内，使用缓存数据
          if (cachedWeather && new Date(cachedWeather.updateTime) > thirtyMinutesAgo) {
            return {
              ...city,
              temperature: cachedWeather.temperature,
              weatherCondition: cachedWeather.weatherCondition,
              text: cachedWeather.weatherCondition,
              icon: getIconCodeFromWeatherCondition(cachedWeather.weatherCondition)
            };
          }
          
          // 否则，获取实时天气数据
          const realTimeData = await weatherApi.getRealTimeWeather(city.id);
          const now = realTimeData.now;
          const weatherCondition = weatherApi.iconCodeToWeatherCondition(now.icon);
          
          // 返回带有天气数据的城市信息
          return {
            ...city,
            temperature: parseFloat(now.temp),
            weatherCondition: weatherCondition,
            text: now.text,
            icon: now.icon
          };
        } catch (error) {
          console.error(`获取城市 ${city.name} 天气数据失败:`, error.message);
          // 如果获取失败，返回原始城市数据
          return city;
        }
      })
    );

    // 创建新的响应对象，包含天气数据
    const enrichedResponse = {
      ...topCitiesData,
      topCityList: enrichedTopCities
    };

    // 返回带有天气数据的响应
    res.status(200).json(enrichedResponse);
    
    // 后台异步保存城市数据到数据库（不阻塞响应）
    saveTopCitiesToDatabase(enrichedTopCities);
  } catch (error) {
    console.error('获取热门城市天气失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
};

/**
 * 根据天气状况获取对应的图标代码
 * @param {string} condition - 天气状况描述
 * @returns {string} 图标代码
 */
function getIconCodeFromWeatherCondition(condition) {
  const conditionIconMap = {
    '晴': '100',
    '多云': '101',
    '少云': '102',
    '晴间多云': '103',
    '阴': '104',
    '阵雨': '300',
    '强阵雨': '301',
    '雷阵雨': '302',
    '强雷阵雨': '303',
    '雷阵雨伴有冰雹': '304',
    '小雨': '305',
    '中雨': '306',
    '大雨': '307',
    '极端降雨': '308',
    '毛毛雨': '309',
    '暴雨': '310',
    '大暴雨': '311',
    '特大暴雨': '312',
    '冻雨': '313',
    '小到中雨': '314',
    '中到大雨': '315',
    '大到暴雨': '316',
    '暴雨到大暴雨': '317',
    '大暴雨到特大暴雨': '318',
    '雨': '399',
    '小雪': '400',
    '中雪': '401',
    '大雪': '402',
    '暴雪': '403',
    '雨夹雪': '404',
    '雨雪天气': '405',
    '阵雨夹雪': '406',
    '阵雪': '407',
    '小到中雪': '408',
    '中到大雪': '409',
    '大到暴雪': '410',
    '雪': '499',
    '薄雾': '500',
    '雾': '501',
    '霾': '502',
    '扬沙': '503',
    '浮尘': '504',
    '沙尘暴': '507',
    '强沙尘暴': '508',
    '热': '900',
    '冷': '901',
    '未知': '999'
  };
  
  return conditionIconMap[condition] || '999';
}

/**
 * 后台保存热门城市数据到数据库
 * @param {Array} cities - 城市列表
 */
async function saveTopCitiesToDatabase(cities) {
  if (!cities || !Array.isArray(cities)) return;
  
  // 异步保存每个城市的基本信息
  cities.forEach(async (city) => {
    try {
      // 获取实时天气数据
      const realTimeData = await weatherApi.getRealTimeWeather(city.id);
      
      // 提取基本数据
      const now = realTimeData.now;
      const weatherCondition = weatherApi.iconCodeToWeatherCondition(now.icon);
      
      // 设置北京时间
      const beijingTime = getBeijingTime();
      const updateTime = new Date(beijingTime);
      
      // 查找或创建天气记录
      let weather = await Weather.findOne({
        where: { city: city.name, province: city.adm1 }
      });
      
      const weatherData = {
        temperature: parseFloat(now.temp),
        humidity: parseFloat(now.humidity),
        windSpeed: parseFloat(now.windSpeed),
        windDirection: now.windDir,
        weatherCondition: weatherCondition,
        updateTime
      };
      
      if (weather) {
        // 更新现有天气记录
        await weather.update(weatherData);
      } else {
        // 创建新天气记录
        await Weather.create({
          city: city.name,
          province: city.adm1,
          date: new Date(),
          ...weatherData
        });
      }
    } catch (error) {
      console.error(`保存城市 ${city.name} 天气数据失败:`, error.message);
    }
  });
}

// 获取北京时间
function getBeijingTime() {
  // 获取当前UTC时间
  const now = new Date();
  // 北京时间是UTC+8
  const beijingTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
  return beijingTime;
}

// 获取城市天气预报详情
exports.getForecastDetail = async (req, res) => {
  try {
    const { city, province } = req.params;
    
    if (!city || !province) {
      return res.status(400).json({
        status: 'fail',
        message: '请提供城市和省份'
      });
    }
    
    // 先从数据库查询是否有该城市的天气预报数据
    const cachedWeather = await Weather.findOne({
      where: { city, province },
      include: [{
        model: Forecast,
        as: 'forecasts'
      }]
    });
    
    // 检查数据是否存在且更新时间是否在2小时内
    const now = new Date();
    const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
    
    // 如果有缓存数据且更新时间在2小时内，且预报数据存在，直接返回缓存数据
    if (cachedWeather && 
        new Date(cachedWeather.updateTime) > twoHoursAgo && 
        cachedWeather.forecasts && 
        cachedWeather.forecasts.length > 0) {
      console.log(`使用缓存的天气预报数据，城市: ${city}, 更新时间: ${cachedWeather.updateTime}`);
      
      // 对预报数据按日期排序
      cachedWeather.forecasts.sort((a, b) => new Date(a.date) - new Date(b.date));
      
      return res.status(200).json({
        status: 'success',
        data: {
          weather: cachedWeather,
          source: '数据库缓存'
        }
      });
    }
    
    // 没有缓存、缓存已过期或没有预报数据，需要请求新数据
    try {
      // 1. 搜索城市获取ID
      const cityData = await weatherApi.searchCity(city, { adm: province });
      if (!cityData.location || cityData.location.length === 0) {
        throw new Error('找不到该城市');
      }
      
      const locationId = cityData.location[0].id;
      console.log(`获取到城市 ${city} 的ID: ${locationId}`);
      
      // 2. 获取实时天气
      const realTimeData = await weatherApi.getRealTimeWeather(locationId);
      console.log(`成功获取实时天气数据`);
      
      // 3. 获取天气预报 (修改为7天)
      const forecastData = await weatherApi.getWeatherForecast(locationId, 7);
      console.log(`成功获取天气预报数据`);
      
      // 4. 获取空气质量
      let airQualityData = null;
      try {
        airQualityData = await weatherApi.getAirQuality(locationId);
        console.log(`成功获取空气质量数据`);
      } catch (error) {
        console.error('获取空气质量失败，将继续处理其他数据:', error.message);
      }
      
      // 5. 转换数据格式
      const weatherData = weatherApi.convertWeatherData(realTimeData, forecastData, airQualityData);
      
      // 6. 保存到数据库（设置北京时间格式）
      const beijingTime = getBeijingTime();
      const updateTime = new Date(beijingTime);
      
      // 如果已有记录则更新，否则创建新记录
      let weather;
      if (cachedWeather) {
        await cachedWeather.update({
          temperature: weatherData.temperature,
          temperatureFeelsLike: weatherData.temperatureFeelsLike,
          temperatureHigh: weatherData.temperatureHigh,
          temperatureLow: weatherData.temperatureLow,
          humidity: weatherData.humidity,
          windSpeed: weatherData.windSpeed,
          windDirection: weatherData.windDirection,
          weatherCondition: weatherData.weatherCondition,
          aqi: weatherData.aqi,
          airQualityLevel: weatherData.airQualityLevel,
          pm25: weatherData.pm25,
          pm10: weatherData.pm10,
          updateTime
        });
        weather = cachedWeather;
      } else {
        weather = await Weather.create({
          city,
          province,
          temperature: weatherData.temperature,
          temperatureFeelsLike: weatherData.temperatureFeelsLike,
          temperatureHigh: weatherData.temperatureHigh,
          temperatureLow: weatherData.temperatureLow,
          humidity: weatherData.humidity,
          windSpeed: weatherData.windSpeed,
          windDirection: weatherData.windDirection,
          weatherCondition: weatherData.weatherCondition,
          aqi: weatherData.aqi,
          airQualityLevel: weatherData.airQualityLevel,
          pm25: weatherData.pm25,
          pm10: weatherData.pm10,
          date: new Date(),
          updateTime
        });
      }
      
      // 7. 更新天气预报
      // 先删除旧的预报数据
      await Forecast.destroy({
        where: { weatherId: weather.id }
      });
      
      // 添加新的预报数据，确保保存所有必要的字段
      const forecastPromises = weatherData.forecast.map(forecast => {
        return Forecast.create({
          weatherId: weather.id,
          date: new Date(forecast.date),
          sunrise: forecast.sunrise,
          sunset: forecast.sunset,
          temperatureHigh: forecast.temperatureHigh,
          temperatureLow: forecast.temperatureLow,
          weatherCondition: forecast.weatherCondition,
          weatherConditionNight: forecast.weatherConditionNight,
          textDay: forecast.textDay,
          textNight: forecast.textNight,
          windSpeed: forecast.windSpeed,
          windDirection: forecast.windDirection,
          windScale: forecast.windScale,
          windSpeedNight: forecast.windSpeedNight,
          windDirectionNight: forecast.windDirectionNight,
          windScaleNight: forecast.windScaleNight,
          humidity: forecast.humidity,
          precipitation: forecast.precipitation,
          pressure: forecast.pressure,
          visibility: forecast.visibility,
          uvIndex: forecast.uvIndex,
          probability: forecast.probability
        });
      });
      
      await Promise.all(forecastPromises);
      
      // 8. 重新查询带有预报的完整天气数据
      const completeWeather = await Weather.findByPk(weather.id, {
        include: [{
          model: Forecast,
          as: 'forecasts'
        }]
      });
      
      // 对预报数据按日期排序
      completeWeather.forecasts.sort((a, b) => new Date(a.date) - new Date(b.date));
      
      return res.status(200).json({
        status: 'success',
        data: {
          weather: completeWeather,
          source: '和风天气API'
        }
      });
    } catch (apiError) {
      console.error('API请求失败:', apiError);
      
      // 如果API请求失败但有缓存数据，返回缓存数据
      if (cachedWeather) {
        console.log(`API请求失败，使用缓存数据`);
        return res.status(200).json({
          status: 'success',
          data: {
            weather: cachedWeather,
            source: '数据库缓存（API请求失败）'
          }
        });
      }
      
      throw apiError;
    }
  } catch (error) {
    console.error('获取天气预报详情失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
}; 